package com.kcsj.controller.basic;
//李延杰
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kcsj.domain.Product;
import com.kcsj.domain.Product;
import com.kcsj.service.ProductService;
import com.kcsj.service.ProductService;
import com.kcsj.util.Condition;
import com.kcsj.util.JSONUtil;
import com.kcsj.util.MessageHelper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@Slf4j
@WebServlet("/product.ctl")
public class ProductController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        try {
            //根据请求反序列化生成对象
            Product product = JSON.parseObject(req_jsonStr,Product.class);
            //添加产品信息
            int id = ProductService.getInstance().add(product);
            JSONObject addMessage = MessageHelper.addMessage("增加成功");
            response.getWriter().println(addMessage);
        } catch (SQLException e) {
            JSONObject dateBaseError = MessageHelper.dateBaseError();
            response.getWriter().println(dateBaseError);
            log.error(e.getMessage());
        } catch (Exception e) {
            JSONObject netWordError = MessageHelper.netWordError();
            e.printStackTrace();
            //响应respMessage_jsonObj到前端
            response.getWriter().println(netWordError);
            //打印异常栈，方便调试
            log.error(e.getMessage());
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String request_jsonstr = JSONUtil.getJSON(request);
        try {
            Product Product = JSON.parseObject(request_jsonstr, Product.class);
            //到数据库表修改Degree对象对应的记录
            boolean judge = ProductService.getInstance().update(Product);
            if (judge) {
                JSONObject addMessage = MessageHelper.addMessage("修改成功");
                response.getWriter().println(addMessage);
            }else {
                JSONObject addMessage = MessageHelper.addMessage("修改异常");
                response.getWriter().println(addMessage);
            }
        } catch (SQLException e) {
            JSONObject dateBaseError = MessageHelper.dateBaseError();
            response.getWriter().println(dateBaseError);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage());
        } catch (Exception e) {
            JSONObject netWordError = MessageHelper.netWordError();
            response.getWriter().println(netWordError);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage());
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从JSONObject对象中读取键“no”的值（Java Object对象），
        String no_obj = request.getParameter("productNo");
        try {
            //到数据库表中删除对应的教师
            boolean judge = ProductService.getInstance().delete(no_obj);
            if (judge) {
                JSONObject addMessage = MessageHelper.addMessage("删除成功");
                response.getWriter().println(addMessage);
            }else {
                JSONObject addMessage = MessageHelper.addMessage("删除失败");
                response.getWriter().println(addMessage);
            }
        } catch (SQLException e) {
            JSONObject dateBaseError = MessageHelper.dateBaseError();
            response.getWriter().println(dateBaseError);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage());
        } catch (Exception e) {
            JSONObject netWordError = MessageHelper.netWordError();
            response.getWriter().println(netWordError);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage());
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取前端请求的信息
        String productNo = request.getParameter("productNo");
        try {
            if(productNo!=null){
                this.responseProduct(response,productNo);
            }else {
                this.responseProducts(response,null);
            }
        }catch (SQLException e){
            JSONObject message = MessageHelper.dateBaseError();
            e.printStackTrace();
            //响应message到前端
            response.getWriter().println(message);
        }catch(Exception e){
            JSONObject message = MessageHelper.netWordError();
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }

    private void responseProduct(HttpServletResponse response, String no) throws SQLException, IOException {
        Product product = ProductService.getInstance().find(no);
        String deliveryPerson_jsonstr= JSON.toJSONString(product);
        JSONObject data = MessageHelper.addData(deliveryPerson_jsonstr);
        response.getWriter().println(data);
    }

    private void responseProducts(HttpServletResponse response,List<Condition> conditionList) throws SQLException, IOException {
        Collection<Product> products = ProductService.getInstance().findAll(conditionList);
        String Products_jsonstr = JSON.toJSONString(products, SerializerFeature.DisableCircularReferenceDetect);
        JSONObject data = MessageHelper.addData(Products_jsonstr);
        //响应resp_jsonObj到前端
        response.getWriter().println(data);
    }

}
